package com.lz.sports.ui.group

import android.os.Bundle
import androidx.databinding.library.baseAdapters.BR
import androidx.lifecycle.lifecycleScope
import com.lz.library.base.BaseFragment
import com.lz.library.extension.click
import com.lz.sports.R
import com.lz.sports.adapter.GroupBindAdapter
import com.lz.sports.databinding.FragmGroupBindBinding
import com.lz.sports.vm.group.GroupBindViewModel
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

//设备绑定
class GroupBindFragment : BaseFragment<GroupBindViewModel, FragmGroupBindBinding>() {

    private val adapter by lazy { GroupBindAdapter() }

    override fun getLayoutRes(): Int = R.layout.fragm_group_bind

    override fun getVMVariableId(): Int = BR.vm

    override fun initObserve() {
        viewModel.deviceInfoList.observe(this) {
            adapter.setNewData(it)
            binding.rvList.scrollToPosition(0)
        }
    }

    override fun initData(savedState: Bundle?) {
        binding.rvList.adapter = adapter
        adapter.itemBindListener = object : GroupBindAdapter.OnItemBindListener {
            override fun onItemBind(position: Int) {
                if (viewModel.bindItem(adapter.getItem(position))) {
                    adapter.removeItem(position)
                    viewModel.totalCount.value = adapter.itemCount
                }
            }
        }

        viewModel.deviceGroup = arguments!!.getParcelable("DeviceGroup")!!
        lifecycleScope.launch {
            arrayOf(binding.ivClear, binding.flSearch).click().collect {
                when (it.id) {
                    R.id.iv_clear -> { binding.etInput.setText(""); viewModel.clearSearch() }
                    R.id.fl_search -> viewModel.search()
                }
            }
        }
    }
}